import rclpy
import time
from rclpy.node import Node
from chapt4_interfaces.srv import Partol
import random
class TurtleClient(Node):
    def __init__(self,node_name):
        super().__init__(node_name)
        self.get_logger().info(f"{node_name} 启动")
        self.client=self.create_client(Partol,'turtle_control') # 客户端名字要和服务端保持以一致

    # 客户端发送请求
    def send_request(self,target_x,target_y):
        # 1 判断服务端是否在线
        while(self.client.wait_for_service(1.0)) is False:
            self.get_logger().info('等待服务端上线')
        # 2 构造request
        request=Partol.Request()
        request.target_x=target_x
        request.target_y=target_y
      
        # 发送请求等待处理相应
        future=self.client.call_async(request) # 需要等待服务端处理完才会把结果放到future中
        
        def result_callback(result_future):
            response=result_future.result() # 获取相应
            self.show_response(response)

        future.add_done_callback(result_callback)


    # 客户端显示相应结果
    def show_response(self,response):
        self.get_logger().info(f"服务端返回结果:{response.result}")

def main():
    rclpy.init()
    node=TurtleClient('turtle_client')
    x=0.0
    y=0.0
    while 1:
        target_x=float(random.randint(0,11))
        target_y=float(random.randint(0,11))
        node.send_request(target_x,target_y)
        x+=1
        y+=1
        time.sleep(5)
    rclpy.spin(node)

    rclpy.shutdown()